<script setup lang="ts">
import { Query, PageVO, classForm, typeList } from "@/api/curriculum/types";
import {
  getClassPage,
  getCateList,
  getSubjectkAdd,
  postDelete,
} from "@/api/curriculum/index";
import type { FormInstance, FormRules } from "element-plus";

const queryFormRef = ref(ElForm); // 查询表单
const loading = ref(false);
const total = ref(0);
const dataList = ref<PageVO[]>([]);
const imgUrl = ref(import.meta.env.VITE_APP_BASE_API);

const queryParams = reactive<Query>({
  page: 1,
  page_size: 10,
});

/**
 * 查询
 */
function handleQuery() {
  loading.value = true;
  getClassPage(queryParams)
    .then(({ data }) => {
      dataList.value = data;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.page = 1;
  handleQuery();
}

// 新增正则验证
const rules = reactive<FormRules>({
  name: [{ required: true, message: "分类名称不能为空", trigger: "blur" }],
  grade_id: [{ required: true, message: "请选择顶级分类", trigger: "change" }],
});

// 打开新增
const formData = reactive<classForm>({
  is_show: 1,
  pic: "",
  grade_id: 0,
});

const dialog = reactive({
  visible: false,
  title: "新增",
});

const selectList = ref<typeList[]>([]);
const openDialog = (data: any | null = null) => {
  dialog.visible = true;
  dialog.title = "新增";
  if (data) {
    formData.id = data.id;
    formData.name = data.name;
    formData.image = imgUrl.value + data.pic;
    formData.sort = data.sort;
    formData.is_show = data.is_show;
    formData.grade_id = data.grade_id;
    dialog.title = "编辑";
  }
  // 获取课程分类顶级列表
  getCateList().then(({ data }) => {
    selectList.value = data;
  });
};

// 提交数据
const ruleFormRef = ref<FormInstance>();
const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let res = (await getSubjectkAdd(formData)) as any;
      ElMessage.success(res.msg);
      resetQuery();
      closeDialog();
    }
  });
};

// 删除
const handleDelete = async (id: number) => {
  await ElMessageBox.confirm("确定要删除吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let res = (await postDelete({ id: id })) as any;
      ElMessage.success(res.msg);
      handleQuery();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};

// 关系弹窗
const closeDialog = () => {
  dialog.visible = false;
};

// 修改url
const updatepostUrl = (url: string) => {
  formData.pic = url;
  formData.image = imgUrl.value + url;
};

onMounted(() => {
  handleQuery(); // 初始化用户列表数据
});
</script>

<template>
  <div class="app-container">
    <!-- 查询 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="分类名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="输入分类名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery"><i-ep-search />搜索</el-button>
          <el-button @click="resetQuery">
            <i-ep-refresh />
            重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between">
          <div>
            <el-button type="success" @click="openDialog()"><i-ep-plus />新增</el-button>
          </div>
        </div>
      </template>
      <el-table
        :data="dataList"
        row-key="id"
        border
        default-expand-all
        :tree-props="{
          children: 'child',
        }"
      >
        <el-table-column prop="name" label="分类名称" />
        <el-table-column prop="pic" label="图片" align="center">
          <template #default="scope">
            <img :src="imgUrl + scope.row.pic" alt="" style="width: 50px; height: 50px" />
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" sortable align="center" />
        <el-table-column label="状态">
          <template #default="scope">
            <!-- <el-switch v-model="scope.row.is_show" :active-value="1" :inactive-value="0" size="small" active-text="显示"
              inactive-text="隐藏" /> -->
            <div v-if="scope.row.is_show == 1">
              <el-tag type="success">显示</el-tag>
            </div>
            <div v-else>
              <el-tag type="danger">隐藏</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="280">
          <template #default="scope">
            <el-button type="primary" size="small" @click="openDialog(scope.row)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button type="danger" size="small" @click="handleDelete(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.page"
        v-model:limit="queryParams.page_size"
        @pagination="handleQuery"
      />
    </el-card>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="600px"
      append-to-body
      @close="closeDialog"
    >
      <el-form ref="ruleFormRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="顶级分类" prop="grade_id">
          <el-select v-model="formData.grade_id" placeholder="选择顶级分类">
            <el-option
              v-for="item in selectList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="图片" v-if="formData.grade_id > 0">
          <single-upload
            @updatepostUrl="updatepostUrl"
            v-model="formData.image"
            type="image"
          />
        </el-form-item>

        <el-form-item label="排序">
          <el-input v-model="formData.sort" placeholder="请输入排序" />
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="formData.is_show">
            <el-radio :label="1">显示</el-radio>
            <el-radio :label="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit(ruleFormRef)">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
